/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeReaderAuto = argot.TypeReaderAuto;
using TypeLibrary = argot.TypeLibrary;
using TypeWriter = argot.TypeWriter;

namespace argot.meta
{
	
	public class MetaEncoding
	:MetaBase, TypeReader, TypeWriter, MetaExpression
	{
		public const System.String TYPENAME = "meta.encoding";
		
		private MetaExpression _expression;
		private System.String _encoding;
		
		public MetaEncoding(MetaExpression expression, System.String encoding)
		{
			_expression = expression;
			_encoding = encoding;
		}

		override public System.String TypeName
		{
			get
			{
				return TYPENAME;
			}
			
		}
		
		public override void Bind(TypeLibrary library, TypeElement definition, System.String typeName, int typeId)
		{
			base.Bind(library, definition, typeName, typeId);
			_expression.Bind(library, definition, typeName, typeId);
		}
		
		public virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			if (element is MetaExpression)
			{
				TypeReader reader = new TypeReaderAuto(this.GetType());
				return reader.Read(inStream, element);
			}
			throw new TypeException("shouldn't get here.");
		}

		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
			MetaEncoding enc = (MetaEncoding) o;
			
			outStream.WriteObject("meta.expression", enc._expression);
			outStream.WriteObject("meta.name", enc._encoding);
		}

		public virtual void DoWrite(TypeOutputStream outStream, System.Object o)
		{
			// TODO Auto-generated method stub
		}

		public virtual System.Object DoRead(TypeInputStream inStream)
		{
			byte[] data = (byte[]) _expression.DoRead(inStream);
			return System.Text.Encoding.GetEncoding(_encoding).GetString(data);
		}
	}
}